package com.wanyangproject.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.base.MyApp;
import com.wanyangproject.entity.DuanXinShiBaiEntity;
import com.wanyangproject.entity.HuoQuYanZhengMaEntity;
import com.wanyangproject.entity.RegisterEntity;
import com.wanyangproject.entity.XieYiEntity;
import com.wanyangproject.entity.ZhuCeShiBaiEntity;
import com.wanyangproject.shouye.ShenFenBangDingActivity;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.SharedPreferencesToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

//  注册
public class RegisterActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_duanxin_yanzhengma)
    EditText etDuanxinYanzhengma;
    @BindView(R.id.tv_huoqu_yanzhengma)
    TextView tvHuoquYanzhengma;
    @BindView(R.id.et_mima_one)
    EditText etMimaOne;
    @BindView(R.id.image_eye_one)
    ImageView imageEyeOne;
    @BindView(R.id.et_mima_two)
    EditText etMimaTwo;
    @BindView(R.id.image_eye_two)
    ImageView imageEyeTwo;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_tongyi)
    TextView tvTongyi;
    @BindView(R.id.image_delete)
    ImageView imageDelete;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    private int num;
    private  HuoQuYanZhengMaEntity huoQuYanZhengMaEntity;
    private RegisterEntity registerEntity;
    private XieYiEntity xieYiEntity;
    private WebView webView;
    private String content;
    private WebSettings mWebSettings;
    private static Boolean isOK = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }








        //                用户协议的网络请求
        initXieYiHttp();







    }

    @OnClick({R.id.image_delete, R.id.tv_register, R.id.image_back, R.id.et_phone, R.id.et_duanxin_yanzhengma, R.id.tv_huoqu_yanzhengma, R.id.et_mima_one, R.id.image_eye_one, R.id.et_mima_two, R.id.image_eye_two, R.id.tv_login, R.id.tv_tongyi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_delete:
                etPhone.setText("");
                break;
//            立即注册
            case R.id.tv_register:
                if(etPhone.getText().toString().trim().equals("")){
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else if(etDuanxinYanzhengma.getText().toString().trim().equals("")){
                    Toast.makeText(this, "请输入短信验证码", Toast.LENGTH_SHORT).show();
                }else if(etMimaOne.getText().toString().trim().equals("")){
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                }else if(etMimaTwo.getText().toString().trim().equals("")){
                    Toast.makeText(this, "请确认密码", Toast.LENGTH_SHORT).show();
                }else{
                    //                注册的网络请求
                    initRegister();
                }


//                final AlertDialog dialog = new AlertDialog.Builder(RegisterActivity.this).create();
//                dialog.show();
//                dialog.getWindow().setContentView(R.layout.bangding_alertdialog);
//                dialog.getWindow().setBackgroundDrawableResource(R.drawable.shape_my_youke);
//                WindowManager windowManager1 = getWindowManager();
//                Display defaultDisplay1 = windowManager1.getDefaultDisplay();
//                WindowManager.LayoutParams attributes1 = dialog.getWindow().getAttributes();
//                attributes1.width= (int) (defaultDisplay1.getWidth()*0.8);
//                dialog.getWindow().setAttributes(attributes1);
//                dialog.getWindow().findViewById(R.id.tv_tiaoguo).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Intent intent = new Intent(RegisterActivity.this, HomeActivity.class);
//                        startActivity(intent);
//                        dialog.dismiss();
//                    }
//                });
//                dialog.getWindow().findViewById(R.id.tv_bangding).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Intent intent = new Intent(RegisterActivity.this, ShenFenBangDingActivity.class);
//                        intent.putExtra("bangding","1");
//                        startActivity(intent);
//                        dialog.dismiss();
//                    }
//                });

                break;
//            返回按钮
            case R.id.image_back:
                finish();
                break;
//            手机号
            case R.id.et_phone:
                break;
//            验证码
            case R.id.et_duanxin_yanzhengma:
                break;
//            获取验证码的按钮
            case R.id.tv_huoqu_yanzhengma:
//                //                判断账号是否注册过
//                initPanDuanShiFouZhuCeGuoHttp();

                if(ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim()) == false){
                    Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(etPhone.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else{
                    //                获取验证码的网络请求
                    initHuoQuYanZhengMaHttp();
                }

                break;
//            输入密码
            case R.id.et_mima_one:
                break;
//            输入密码眼睛
            case R.id.image_eye_one:
                if (isOK) {
//                    如果选中显示密码
                    imageEyeOne.setImageResource(R.mipmap.close_eye);
                    etMimaOne.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isOK = false;
                } else {
//                    否则隐藏密码
                    imageEyeOne.setImageResource(R.mipmap.open_eye);
                    etMimaOne.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isOK = true;
                }
                break;
//           确认输入密码
            case R.id.et_mima_two:
                break;
//            输入密码眼睛
            case R.id.image_eye_two:
                if (isOK) {
//                    如果选中显示密码
                    imageEyeTwo.setImageResource(R.mipmap.close_eye);
                    etMimaTwo.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isOK = false;
                } else {
//                    否则隐藏密码
                    imageEyeTwo.setImageResource(R.mipmap.open_eye);
                    etMimaTwo.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isOK = true;
                }
                break;
//            登录
            case R.id.tv_login:
                Intent intent1 = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent1);
                break;
//            同意
            case R.id.tv_tongyi:


                System.out.println(xieYiEntity.getResponse().getContent()+"          xieYiEntity.getResponse().getContent()");


                final AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).create();
                alertDialog.show();
                alertDialog.getWindow().setContentView(R.layout.register_xieyi_alertdialog);
                alertDialog.getWindow().setBackgroundDrawableResource(R.drawable.shape_zhuce);
                alertDialog.setCancelable(false);
                WindowManager windowManager=getWindowManager();
                Display defaultDisplay = windowManager.getDefaultDisplay();
                WindowManager.LayoutParams attributes = alertDialog.getWindow().getAttributes();
                attributes.width= (int) (defaultDisplay.getWidth()*0.8);
                alertDialog.getWindow().setAttributes(attributes);
                webView = alertDialog.getWindow().findViewById(R.id.webView);
                if(xieYiEntity.getResponse().getContent() != null){
                    //   内容
                    content = xieYiEntity.getResponse().getContent();
                    webView.loadDataWithBaseURL("http://www.baidu.com", content,"text/html", "UTF-8", null);
//                    webView.loadDataWithBaseURL("http://www.baidu.com", getNewContent(content),"text/html", "UTF-8", null);
                }
                alertDialog.getWindow().findViewById(R.id.tv_yuedu).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
                alertDialog.getWindow().findViewById(R.id.image_quxiao).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
                break;
        }
    }









    //    判断账号是否注册过
    private void initPanDuanShiFouZhuCeGuoHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"index/sendsmswei")
                .addParams("phone",etPhone.getText().toString().trim())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"         判断账号是否注册过 ");
                    }
                });
    }







    //    用户协议的网络请求
    private void initXieYiHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"index/xieyi")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e+"       eeeee用户协议");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"                 用户协议的网络请求");
                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            xieYiEntity = gson.fromJson(response, XieYiEntity.class);
                            System.out.println(xieYiEntity.getResponse().getContent()+"            xieixieyixieyi");
                        }
                    }
                });
    }










    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext){

//        if(isOK == false){
//            return htmltext;
//        }
//
//        isOK = true;
        try {
            Document doc= Jsoup.parse(htmltext);
            Elements elements=doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width","100%").attr("height","auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }








    //    注册的网络请求
    private void initRegister() {

        if(ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim()) == false){
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim());


        if(!(etMimaOne.getText().toString().trim().length() >= 6 && etMimaOne.getText().toString().trim().length() <= 20)){
            Toast.makeText(this, "请输入6-20位的密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if( !etMimaTwo.getText().toString().trim().equals(etMimaOne.getText().toString().trim()) ){
            Toast.makeText(this, "两次密码输入不一样", Toast.LENGTH_SHORT).show();
            return;
        }
        
            
        if(huoQuYanZhengMaEntity == null){
            Toast.makeText(this, "请填写正确的验证码！", Toast.LENGTH_SHORT).show();
            return;
        }    
        

        System.out.println(huoQuYanZhengMaEntity.getResponse().getAuthId()+"     验证码id");



        final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"user/register")
                .addParams("phone",etPhone.getText().toString().trim())
                .addParams("password",etMimaOne.getText().toString().trim())
                .addParams("repwd",etMimaTwo.getText().toString().trim())
                .addParams("code",etDuanxinYanzhengma.getText().toString().trim())
                .addParams("authId",huoQuYanZhengMaEntity.getResponse().getAuthId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"      注册的网络请求");
                        ContractUtils.Code500(RegisterActivity.this,response);
                        progressDialog.dismiss();
                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            registerEntity = gson.fromJson(response, RegisterEntity.class);
                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
//                            注册成功之后保存Token   绑定身份用
                            SharedPreferencesToken.saveRegisterToken(MyApp.getContext(),registerEntity.getResponse().getToken());
                            ContractUtils.setTOKEN(registerEntity.getResponse().getToken());
                            ContractUtils.setParkId(registerEntity.getResponse().getParkInfo().getParkId());
                            ContractUtils.setPhone(registerEntity.getResponse().getUsername());
                            ContractUtils.setYuanquname(registerEntity.getResponse().getParkInfo().getParkName());

                            AlertDialog dialog = new AlertDialog.Builder(RegisterActivity.this).create();
                            dialog.show();
                            dialog.getWindow().setContentView(R.layout.bangding_alertdialog);
                            dialog.getWindow().setBackgroundDrawableResource(R.drawable.shape_zhuce);
                            WindowManager windowManager=getWindowManager();
                            Display defaultDisplay = windowManager.getDefaultDisplay();
                            WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                            attributes.width= (int) (defaultDisplay.getWidth()*0.8);
                            dialog.getWindow().setAttributes(attributes);
                            dialog.getWindow().findViewById(R.id.tv_tiaoguo).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(RegisterActivity.this, HomeActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            });
                            dialog.getWindow().findViewById(R.id.tv_bangding).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(RegisterActivity.this, ShenFenBangDingActivity.class);
                                    intent.putExtra("bangding","1");
                                    startActivity(intent);
                                    finish();
                                }
                            });
                        }else if(response.indexOf("400") != -1){
                            Gson gson = new Gson();
                            ZhuCeShiBaiEntity zhuCeShiBaiEntity = gson.fromJson(response, ZhuCeShiBaiEntity.class);
                            Toast.makeText(RegisterActivity.this, zhuCeShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }



    //    获取短信验证码的网络请求
    private void initHuoQuYanZhengMaHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"index/sendsmsphone")
                .addParams("phone",etPhone.getText().toString().trim())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(RegisterActivity.this,response);
                        System.out.println(response+"     获取验证码的网络请求");

                        if(response.indexOf("200") != -1){
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    try {
                                        num = 60;
                                        while (num > 0) {
//                                          不可点击
                                            tvHuoquYanzhengma.setClickable(false);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                  tvHuoquYanzhengma.setText(num+"s后重新获取");
                                                }
                                            });
                                            Thread.sleep(1000);
                                            num = num - 1;
                                        }

                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                tvHuoquYanzhengma.setClickable(true);
                                                tvHuoquYanzhengma.setText("重新获取");
                                            }
                                        });
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();

                            Gson gson = new Gson();
                            huoQuYanZhengMaEntity = gson.fromJson(response, HuoQuYanZhengMaEntity.class);
                            Toast.makeText(RegisterActivity.this, huoQuYanZhengMaEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }else if(response.indexOf("400") != -1){
                            ContractUtils.Code400(RegisterActivity.this,response);
//                            Gson gson = new Gson();
//                            DuanXinShiBaiEntity duanXinShiBaiEntity = gson.fromJson(response, DuanXinShiBaiEntity.class);
//                            Toast.makeText(RegisterActivity.this, duanXinShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }












//    //    获取短信验证码的网络请求
//    private void initHuoQuYanZhengMaHttp() {
//        OkHttpUtils.post()
//                .url(ContractUtils.LOGIN_URL+"index/sendsms")
//                .addParams("phone",etPhone.getText().toString().trim())
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        ContractUtils.Code500(RegisterActivity.this,response);
//                        System.out.println(response+"     获取验证码的网络请求");
//
//                        if(response.indexOf("200") != -1){
//                            new Thread() {
//                                @Override
//                                public void run() {
//                                    super.run();
//                                    try {
//                                        num = 60;
//                                        while (num > 0) {
////                                不可点击
//                                            tvHuoquYanzhengma.setClickable(false);
//                                            runOnUiThread(new Runnable() {
//                                                @Override
//                                                public void run() {
////                                        tvHuoquYanzhengma.setBackgroundResource(R.drawable.shape_huoqu_huise);
////                                        tvHuoquYanzhengma.setText("倒计时"+num+"s");
//                                                    tvHuoquYanzhengma.setText(num+"s后重新获取");
//                                                }
//                                            });
//
//                                            Thread.sleep(1000);
//                                            num = num - 1;
//
//                                        }
//                                        tvHuoquYanzhengma.setClickable(true);
//                                        runOnUiThread(new Runnable() {
//                                            @Override
//                                            public void run() {
////                                    tvHuoquYanzhengma.setBackgroundResource(R.drawable.shape_huoqu);
//                                                tvHuoquYanzhengma.setText("重新获取");
//                                            }
//                                        });
//
//                                    } catch (InterruptedException e) {
//                                        e.printStackTrace();
//                                    }
//
//                                }
//                            }.start();
//
//                            Gson gson = new Gson();
//                            huoQuYanZhengMaEntity = gson.fromJson(response, HuoQuYanZhengMaEntity.class);
//                            Toast.makeText(RegisterActivity.this, huoQuYanZhengMaEntity.getMsg(), Toast.LENGTH_SHORT).show();
//                        }else if(response.indexOf("400") != -1){
//                            Gson gson = new Gson();
//                            DuanXinShiBaiEntity duanXinShiBaiEntity = gson.fromJson(response, DuanXinShiBaiEntity.class);
//                            Toast.makeText(RegisterActivity.this, duanXinShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });
//    }
}
